﻿using Authentication.Core.Data;
using Authentication.Model.Interface;
using Authentication.Model.Model;
using Common.Contract.Authentication.Record;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using Common.Contract.SystemConfig.Record;
using Authentication.Core.Configuration;
using Common.Data.Repository.Enum;
using Common.Util;
using System;
using System.Globalization;
using Common.Contract.Paging;

namespace Authentication.Provider
{
    public class RequestDaoProvider : GenericProvider, IRequestDaoProvider
    {
        #region Dao Manager
        public bool SaveDaoRequest(CreateDaoRequest userQuestion)
        {
            CreateDaoRequest checkRecord = CheckDaoRequest(userQuestion);
            if (checkRecord == null)
            {
                repository.CreateDaoRequests.Add(userQuestion);
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }

        private CreateDaoRequest CheckDaoRequest(CreateDaoRequest userQuestion)
        {
            return repository.FindOne<CreateDaoRequest>(x => x.StaffId.Equals(userQuestion.StaffId) && x.Cif.Equals(userQuestion.Cif) && x.Email.Equals(userQuestion.Email) && x.Phone.Equals(userQuestion.Phone) && x.Status != (int)StatusRequestCreateDaoEnum.Reject);
        }
        public bool SaveListCreateDaoRequest(List<CreateDaoRequest> listCreateDaoRequest)
        {
            bool isSuccess = true;
            List<string> listDuplicate = new List<string>();
            listCreateDaoRequest.ForEach(request =>
            {
                var checkRecord = CheckDaoRequest(request);
                if (checkRecord == null)
                {
                    repository.CreateDaoRequests.Add(request);
                }
                else
                {
                    listDuplicate.Add(request.StaffId);
                    isSuccess = false;
                }

            });

            if (isSuccess)
            {
                repository.UnitOfWork.SaveChanges();
            }
            return isSuccess;
        }
        public List<CreateDaoRequest> RetrieveListCreateDaoRequest(out int totalRecord, UserRecord currentUser, FilterRecord textSearch = null, int pagesize = 0, int pageindex = 0, SortRecord sortRecord = null)
        {
            int curIdGroup = int.Parse(currentUser.GroupIdentifier);
            var data = repository.DbContext as AuthenticationEntities;
            var query = from x in data.CreateDaoRequests.Include(x => x.Branch)
                        select x;
            if (currentUser.GroupIdentifier.Equals("6") || currentUser.GroupIdentifier.Equals("4"))
            {
                query = query.Where(x => x.Pic.Equals(currentUser.UserName));
            }
            if (SystemConfiguration.UserMBDApprovedDao.Contains(currentUser.UserName))
            {
                query = query.Where(x => x.Branch.Region.Contains("MBD"));
            }
            if (SystemConfiguration.UserHOApprovedDao.Contains(currentUser.UserName))
            {
                query = query.Where(x => x.Status != (int)StatusRequestCreateDaoEnum.Request);
            }
            if (textSearch.CreateDaoRequestStatus.HasValue)
            {
                query = query.Where(x => x.Status == textSearch.CreateDaoRequestStatus);
            }
            else
            {
                query = query.Where(x => string.IsNullOrEmpty(x.RejectPerson) || x.GroupIdReject.Value <= curIdGroup);
            }
            if (textSearch.IsExport == true)
            {
                query = query.Where(x => x.Status == (int)StatusRequestCreateDaoEnum.BranchApproved || x.Status == (int)StatusRequestCreateDaoEnum.RegionApproved);
            }
            if (currentUser.UserName.Equals(SystemConfiguration.UserBICApprovedDao))
            {
                query = query.Where(x => x.Status != (int)StatusRequestCreateDaoEnum.Request);
            }

            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                query = query.Where(x => textSearch.Region.ToUpper().Contains(x.Branch.Region.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                query = query.Where(x => textSearch.Branch.ToUpper().Contains(x.Branch.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.RequestId))
            {
                query = query.Where(x => ("CD" + x.Id.ToString()).Contains(textSearch.RequestId));
            }
            if (!string.IsNullOrEmpty(textSearch.DaoName))
            {
                query = query.Where(x => x.FullName.Contains(textSearch.DaoName));
            }
            if (!string.IsNullOrEmpty(textSearch.StaffId))
            {
                query = query.Where(x => x.StaffId.Contains(textSearch.StaffId));
            }
            if (!string.IsNullOrEmpty(textSearch.ContractType))
            {
                query = query.Where(x => x.PositionName.Contains(textSearch.ContractType));
            }
            if (!string.IsNullOrEmpty(textSearch.Email))
            {
                query = query.Where(x => x.Email.Contains(textSearch.Email));
            }
            if (!string.IsNullOrEmpty(textSearch.RequestStatus) && textSearch.RequestStatus != "-1")
            {
                int requestStatus = int.Parse(textSearch.RequestStatus);
                switch (requestStatus)
                {
                    case 9:
                        query = query.Where(x => x.Status == (int)StatusRequestCreateDaoEnum.Reject && x.GroupIdReject == 3);
                        break;
                    case 10:
                        query = query.Where(x => x.Status == (int)StatusRequestCreateDaoEnum.Reject && x.GroupIdReject == 2);
                        break;
                    case 11:
                        query = query.Where(x => x.Status == (int)StatusRequestCreateDaoEnum.Reject && SystemConfiguration.UserBICApprovedDao.Contains(x.RejectPerson));
                        break;
                    case 12:
                        query = query.Where(x => x.Status == (int)StatusRequestCreateDaoEnum.Reject && x.Pic.Equals(x.RejectPerson));
                        break;
                    default:
                        query = query.Where(x => x.Status == requestStatus);
                        break;
                }
            }
            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.CusOpenDate))
            {
                List<string> listFilter = textSearch.CusOpenDate.Split('-').ToList();
                FromDateCompare = DateTime.ParseExact(listFilter.FirstOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                ToDateCompare = DateTime.ParseExact(listFilter.LastOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                query = query.Where(x => x.CreatedDate >= FromDateCompare && x.CreatedDate <= ToDateCompare);
            }

            totalRecord = query.Count();
            bool isAsc = true;
            if (sortRecord != null && sortRecord.SortDir.Count > 0)
            {
                isAsc = sortRecord.SortDir.FirstOrDefault().Equals("asc");

            }
            if (isAsc)
            {
                query = query.OrderBy(x => x.Id);
            }
            else
            {
                query = query.OrderByDescending(x => x.Id);
            }
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }

        public CreateDaoRequest RetrieveRequestByRequestId(int requestId, UserRecord currentUser)
        {
            var data = repository.DbContext as AuthenticationEntities;
            var query = from x in data.CreateDaoRequests.Include(x => x.Branch)
                        where x.Id == requestId
                        select x;
            if (currentUser.GroupIdentifier.Equals("3"))
            {
                query = query.Where(x => x.BranchId.Equals(currentUser.BranchCode));
            }
            if (currentUser.UserName.Equals(SystemConfiguration.UserBICApprovedDao))
            {
                query = query.Where(x => x.Status != (int)StatusRequestCreateDaoEnum.Request);
            }
            return query.FirstOrDefault();
        }
        public bool UpdateStatusRequestCreateDao(CreateDaoRequest checkUser)
        {
            var checkRecord = repository.FindOne<CreateDaoRequest>(x => x.Id == checkUser.Id);
            if (checkRecord == null)
            {
                return false;
            }
            else
            {
                if (checkRecord.Status == (int)StatusRequestCreateDaoEnum.Reject)
                {
                    checkRecord.GroupIdReject = checkUser.GroupIdReject;
                    checkRecord.RejectPerson = checkUser.RejectPerson;
                }
                checkRecord.Status = checkUser.Status;
                repository.UnitOfWork.SaveChanges();
                return true;
            }
        }
        public bool UpdateOfferLetter(CreateDaoRequest request)
        {
            var checkRecord = repository.FindOne<CreateDaoRequest>(x => x.Id == request.Id);
            if (checkRecord == null)
            {
                return false;
            }
            else
            {
                checkRecord.LinkOfferLetter = request.LinkOfferLetter;
                repository.UnitOfWork.SaveChanges();
                return true;
            }
        }
        public bool UpdateRejectReason(CreateDaoRequest request)
        {
            var checkRecord = repository.FindOne<CreateDaoRequest>(x => x.Id == request.Id);
            if (checkRecord == null)
            {
                return false;
            }
            else
            {
                checkRecord.RejectReason = request.RejectReason;
                checkRecord.RejectPerson = request.RejectPerson;
                checkRecord.GroupIdReject = request.GroupIdReject;
                repository.UnitOfWork.SaveChanges();
                return true;
            }
        }
        public bool UpdateStatusListCreateDaoRequest(int[] listId, int status)
        {
            var listCheckRecord = repository.Find<CreateDaoRequest>(x => listId.Contains(x.Id)).ToList();
            if (listCheckRecord != null && listCheckRecord.Count() > 0)
            {
                listCheckRecord.ForEach(x =>
                {
                    x.Status = status;
                });
            }
            repository.UnitOfWork.SaveChanges();
            return true;
        }
        public bool UpdateListResultCreateDaoRequest(List<CreateDaoRequest> listCreateDaoRequest)
        {
            listCreateDaoRequest.ForEach(x =>
            {
                var check = repository.FindOne<CreateDaoRequest>(y => y.Cif.Equals(x.Cif) && y.StaffId.Equals(x.StaffId) && y.Status == (int)StatusRequestCreateDaoEnum.ITProcessing);
                if (check != null)
                {
                    check.Dao = x.Dao;
                    check.Status = x.Status;
                }
                repository.UnitOfWork.SaveChanges();
            });
            return true;
        }

        #endregion
    }
}
